(define-module (send-email-msmtp)
  #:use-module (ice-9 popen)
  #:use-module (srfi srfi-19)
  #:export (send-email))

  ;; see the last line from this page:
  ;; https://www.gnu.org/software/guile/manual/html_node/Random.html
(set! *random-state* (random-state-from-platform))

(define (send-email to subject body)
  (let ((port (open-pipe* OPEN_WRITE "msmtp" to)))
    (display (email-rfc-2822 subject body) port)
    (close-pipe port)))

(define (email-rfc-2822 subject body)
  (string-append
   ;;"From: joshua@gnucode.me"
   "Subject: " subject "\n"
   ;; email date format: https://datatracker.ietf.org/doc/html/rfc5322#section-3.3
   (string-append "Date: " (date->string (current-date) "~a, ~e ~b ~Y ~T ~z") "\n")
   ;;
   (string-append "Message-ID: <"
                  (number->string (random 1000000 *random-state*))
                  "@local.machine.example>\n\n")
   body))

(send-email "jbranso@dismail.de"
            "I hopefully have dkim?"
            "This is another test email for joshua@gnucode.me")
